<template>
  <div>
    <a-card :bordered="false" title="控制目标">
      <a-button :style="{ marginBottom: '1rem' }" type="danger" @click="showDrawer"> 添加 </a-button>

      <a-table
        :columns="columns"
        :data-source="data"
        style="margin-top: 10px"
        :rowKey="
          (record, index) => {
            return index
          }
        "
        bordered
        :pagination="{ pageSize: 20 }"
      >
        <template
          v-for="col in ['flupDate', 'organization', 'status', 'doctorName', 'receiver']"
          :slot="col"
          slot-scope="text, record"
        >
          <div :key="col">
            <a-input
              v-if="record.editable"
              style="margin: -5px 0"
              :value="text"
              @change="e => handleChange(e.target.value, record.key, col)"
            />
            <template v-else>
              {{ text }}
            </template>
          </div>
        </template>
        <template slot="operation" slot-scope="text, record, index">
          <div class="editable-row-operations">
            <span v-if="record.editable">
              <a @click="() => save(record.key)">Save</a>
              <a-popconfirm title="Sure to cancel?" @confirm="() => cancel(record.key)">
                <a>Cancel</a>
              </a-popconfirm>
            </span>
            <span v-else>
              <a-button @click="show(index)"> 修改 </a-button>
            </span>
          </div>
        </template>
      </a-table>
    </a-card>
    <a-drawer title="控制目标" :width="720" :visible="visible" :body-style="{ paddingBottom: '80px' }" @close="onClose">
      <a-form :form="form" :label-col="{ span: 5 }" :wrapper-col="{ span: 16 }">
        <a-form-item label="控制目标" style="margin-left: 100px">
          <a-input
            style="width: 70%; margin-bottom: 20px"
            :maxLength="12"
            v-decorator="['targetName', { rules: [{ required: true, message: '请输入控制目标名称！' }] }]"
            placeholder="请输入控制目标"
          />
        </a-form-item>
      </a-form>

      <div>
        <a-checkbox
          :checked="area1"
          @change="
            () => {
              area1 = !area1
            }
          "
          ><span style="font-size: 20px">体格</span></a-checkbox
        >
      </div>
      <template v-if="area1">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="BMI">
              <span v-if="height">{{
                weight && height ? (weight / ((height / 100) * (height / 100))).toFixed(2) : ''
              }}</span>
              <a-input-number
                v-else
                :step="0.1"
                :min="0"
                style="width: 320px"
                v-decorator="['BMI']"
                v-model="bmi"
                placeholder="请输入测量值"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="体重（KG）">
              <a-input-number
                :step="0.01"
                style="width: 320px"
                v-decorator="['体重（KG）']"
                v-model="weight"
                placeholder="请输入测量值"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="腰围（cm）">
              <a-input-number
                :step="0.01"
                style="width: 320px"
                v-decorator="['腰围（cm）']"
                v-model="waist"
                placeholder="请输入测量值"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="心率/脉搏（次/分钟）">
              <a-input-number
                :step="1"
                style="width: 320px"
                v-decorator="['心率/脉搏（次/分钟）']"
                v-model="heartRate"
                placeholder="请输入测量值"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="收缩压（mmHg）">
              <a-input-number
                :step="1"
                style="width: 320px"
                v-decorator="['收缩压（mmHg）']"
                v-model="pressureHigh"
                placeholder="请输入测量值"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="舒张压（mmHg）">
              <a-input-number
                :step="1"
                style="width: 320px"
                v-decorator="['舒张压（mmHg）']"
                v-model="pressureLow"
                placeholder="请输入测量值"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </template>

      <div>
        <a-checkbox
          :checked="area2"
          @change="
            () => {
              area2 = !area2
            }
          "
          ><span style="font-size: 20px">血糖</span></a-checkbox
        >
      </div>
      <template v-if="area2">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="空腹血糖（mmol/L）">
              <a-input-number
                :step="0.1"
                style="width: 320px"
                v-decorator="['空腹血糖（mmol/L）']"
                v-model="fbg"
                placeholder="请输入测量值"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="餐后血糖（mmol/L）">
              <a-input-number
                :step="0.1"
                style="width: 320px"
                v-decorator="['餐后血糖（mmol/L）']"
                v-model="pbg"
                placeholder="请输入测量值"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="糖化血红蛋白">
              <a-input-number
                :step="0.1"
                style="width: 320px"
                v-decorator="['糖化血红蛋白']"
                v-model="hbA1c"
                placeholder="请输入测量值"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </template>

      <div>
        <a-checkbox
          :checked="area3"
          @change="
            () => {
              area3 = !area3
            }
          "
          ><span style="font-size: 20px">血脂</span></a-checkbox
        >
      </div>
      <template v-if="area3">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="总胆固醇（mmol/L）">
              <a-input-number
                :step="0.01"
                style="width: 320px"
                v-decorator="['总胆固醇（mmol/L）']"
                v-model="tc"
                placeholder="请输入测量值"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="甘油三酯（mmol/L）">
              <a-input-number
                :step="0.01"
                style="width: 320px"
                v-decorator="['甘油三酯（mmol/L）']"
                v-model="tg"
                placeholder="请输入测量值"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="低密度脂蛋白胆固醇（mmol/L）">
              <a-input-number
                :step="0.01"
                style="width: 320px"
                v-decorator="['低密度脂蛋白胆固醇（mmol/L）']"
                v-model="ldl"
                placeholder="请输入测量值"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="高密度脂蛋白胆固醇（mmol/L）">
              <a-input-number
                :step="0.01"
                style="width: 320px"
                v-decorator="['高密度脂蛋白胆固醇（mmol/L）']"
                v-model="hdl"
                placeholder="请输入测量值"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </template>

      <div>
        <a-checkbox
          :checked="area4"
          @change="
            () => {
              area4 = !area4
            }
          "
          ><span style="font-size: 20px">肝功能</span></a-checkbox
        >
      </div>
      <template v-if="area4">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="谷丙转氨酶（ALT）（U/L）">
              <a-input-number
                :step="0.01"
                style="width: 320px"
                v-decorator="['谷丙转氨酶（ALT）（U/L）']"
                v-model="alt"
                placeholder="请输入测量值"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="总胆红素（T-BIL）（umol/L）">
              <a-input-number
                :step="0.01"
                style="width: 320px"
                v-decorator="['总胆红素（T-BIL）（umol/L）']"
                v-model="bil"
                placeholder="请输入测量值"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="谷草转氨酶（AST）（U/L）">
              <a-input-number
                :step="0.01"
                style="width: 320px"
                v-decorator="['谷草转氨酶（AST）（U/L）']"
                v-model="ast"
                placeholder="请输入测量值"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="碱性磷酸酶（ALP）（U/L）">
              <a-input-number
                :step="0.01"
                style="width: 320px"
                v-decorator="['碱性磷酸酶（ALP）（U/L）']"
                v-model="alp"
                placeholder="请输入测量值"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </template>

      <div>
        <a-checkbox
          :checked="area5"
          @change="
            () => {
              area5 = !area5
            }
          "
          ><span style="font-size: 20px">肾功能</span></a-checkbox
        >
      </div>
      <template v-if="area5">
        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="尿微量白蛋白（UAE）（ug/min）">
              <a-input-number
                :step="0.01"
                style="width: 320px"
                v-decorator="['尿微量白蛋白（UAE）（ug/min）']"
                v-model="uae"
                placeholder="请输入测量值"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="24h尿白蛋白（24hUAE）（mg/24h）">
              <a-input-number
                :step="0.01"
                style="width: 320px"
                v-decorator="['24h尿白蛋白（24hUAE）（mg/24h）']"
                v-model="uae_24h"
                placeholder="请输入测量值"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="尿白蛋白/尿肌酐（ACR）（mg/g）">
              <a-input-number
                :step="0.01"
                style="width: 320px"
                v-decorator="['尿白蛋白/尿肌酐（ACR）（mg/g）']"
                v-model="acr"
                placeholder="请输入测量值"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="血清肌酐（Cr）（ummol/L）">
              <a-input-number
                :step="0.01"
                style="width: 320px"
                v-decorator="['血清肌酐（Cr）（ummol/L）']"
                v-model="cr"
                placeholder="请输入测量值"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="尿素氮（mmol/L）">
              <a-input-number
                :step="0.01"
                style="width: 320px"
                v-decorator="['尿素氮（mmol/L）']"
                v-model="ureanitrogen"
                placeholder="请输入测量值"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="肾小球滤过率（GFR）">
              <a-input-number
                :step="0.01"
                style="width: 320px"
                v-decorator="['肾小球滤过率（GFR）']"
                v-model="gfr"
                placeholder="请输入测量值"
              />
            </a-form-item>
          </a-col>
        </a-row>

        <a-row :gutter="16">
          <a-col :span="12">
            <a-form-item label="内生肌酐清除率">
              <a-input-number
                :step="0.01"
                style="width: 320px"
                v-decorator="['内生肌酐清除率']"
                v-model="crcl"
                placeholder="请输入测量值"
              />
            </a-form-item>
          </a-col>
          <a-col :span="12">
            <a-form-item label="血尿酸（mmol/L）">
              <a-input-number
                :step="0.01"
                style="width: 320px"
                v-decorator="['血尿酸（mmol/L）']"
                v-model="bua"
                placeholder="请输入测量值"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </template>

      <a-row :gutter="16">
        <a-col :span="24">
          <a-form-item label="用药情况">
            <a-textarea
              v-decorator="['用药情况']"
              :maxLength="300"
              :rows="4"
              v-model="drug"
              placeholder="请输入300字以内的用药情况"
            />
            <div v-if="drug != null && drug.length > 0" :style="{ display: 'inline-block', marginLeft: '34rem' }">
              已填写：{{ drug.length }}/300
            </div>
          </a-form-item>
        </a-col>
      </a-row>

      <div
        :style="{
          position: 'absolute',
          right: 0,
          bottom: 0,
          width: '100%',
          borderTop: '1px solid #e9e9e9',
          padding: '10px 16px',
          background: '#fff',
          textAlign: 'right',
          zIndex: 1
        }"
      >
        <a-button :style="{ marginRight: '8px' }" @click="onClose"> 取消 </a-button>
        <a-button type="primary" @click="postTarget"> 确认 </a-button>
      </div>
    </a-drawer>
  </div>
</template>
<script>
import { postAction, getAction } from '@/api/manage'

import { PAGE_MENU_TYPE } from '@/store/mutation-types'

const columns = [
  // {
  //   title: '序号',
  //   dataIndex: 'dataId',
  //   width: 120,
  // },
  {
    title: '时间',
    dataIndex: 'startDate'
  },
  {
    title: '目标名称',

    dataIndex: 'targetName'
  },
  {
    title: '操作',

    dataIndex: 'operation',
    scopedSlots: { customRender: 'operation' }
  }
]
const columns1 = [
  {
    title: '序号',

    dataIndex: 'dataId',
    width: 120
  },
  {
    title: '时间',

    dataIndex: 'startDate'
  },
  {
    title: '目标名称',

    dataIndex: 'targetName'
  },
  {
    title: '操作',

    dataIndex: 'operation',
    scopedSlots: { customRender: 'operation' }
  }
]

const data = []
const data1 = []
export default {
  name: 'target',
  data() {
    this.cacheData = data.map(item => ({ ...item }))

    return {
      data,
      data1,
      columns1,
      columns,
      visitMonth: '',
      pagination1: false,
      form: this.$form.createForm(this),
      visible: false,
      visitTime: '',
      visitDate: '',
      advise: '',
      name: '',
      heartRate: '',
      ldl: '',
      hdl: '',
      tg: '',
      tc: '',
      alt: '',
      bil: '',
      ast: '',
      alp: '',
      uae: '',
      uae_24h: '',
      acr: '',
      cr: '',
      ureanitrogen: '',
      gfr: '',
      crcl: '',
      pressureHigh: '',
      pressureLow: '',
      pbg: '',
      fbg: '',
      hbA1c: '',
      targetName: '',
      targetId: '',
      bmi: '',
      weight: '',
      height: '',
      waist: '',
      bua: '',
      drug: '',
      formLayout: 'horizontal',
      form: this.$form.createForm(this, { name: 'coordinated' }),
      area1: true,
      area2: true,
      area3: true,
      area4: false,
      area5: false,

      url: {
        getTargetList: '107/02/1070201',
        getTargetValue: '107/02/1070202',
        postTarget: '107/02/1070203'
      },

      editingKey: '',
      queryParam: { patientId: this.$route.query[PAGE_MENU_TYPE.PatientId] }
    }
  },
  created() {
    this.getTime()
    this.getInfo()
    this.getTargetList()
  },
  methods: {
    getInfo() {
      let patientId = this.$route.query[PAGE_MENU_TYPE.PatientId]
      getAction('102/11/1021102', {
        patientId: patientId
      }).then(res => {
        if (res.success) {
          this.height = res.result.height
        }
      })
    },
    add() {
      this.visible = true
    },
    showDrawer() {
      this.cleanForm()
      this.visible = true
    },
    onClose() {
      this.visible = false
    },
    postTarget() {
      this.form.validateFields((err, values) => {
        if (!err) {
          if (this.height) {
            this.bmi =
              this.weight && this.height ? (this.weight / ((this.height / 100) * (this.height / 100))).toFixed(2) : ''
          }
          let params = {
            targetId: this.targetId,
            patientId: this.queryParam.patientId,
            heartRate: this.heartRate,
            ldl: this.ldl,
            bua: this.bua,
            hdl: this.hdl,
            tg: this.tg,
            tc: this.tc,
            alt: this.alt,
            bil: this.bil,
            ast: this.ast,
            alp: this.alp,
            uae: this.uae,
            uae_24h: this.uae_24h,
            acr: this.acr,
            cr: this.cr,
            ureanitrogen: this.ureanitrogen,
            gfr: this.gfr,
            crcl: this.crcl,
            pressureHigh: this.pressureHigh,
            pressureLow: this.pressureLow,
            pbg: this.pbg,
            fbg: this.fbg,
            hbA1c: this.hbA1c,
            targetId: this.targetId,
            bmi: this.bmi,
            waist: this.waist,
            weight: this.weight,
            targetName: values.targetName,
            drug: this.drug
          }
          postAction(this.url.postTarget, params).then(res => {
            if (res.success) {
              this.$message.success('控制目标保存成功！')

              this.onClose()
              this.getTargetList()
            }
          })
        }
      })
    },

    getTargetList() {
      this.data = []
      let params = {
        patientId: this.queryParam.patientId
      }
      postAction(this.url.getTargetList, params).then(res => {
        if (res.success) {
          for (let i = 0; i < res.result.total; i++) {
            this.data.push({
              dataId: res.result.records[i].dataId,
              startDate: res.result.records[i].createTime,
              targetName: res.result.records[i].targetName
            })
          }
          console.log(this.data)
        }
      })
    },
    getTime() {
      var myDate = new Date()
      var tYear = myDate.getFullYear()
      var tMonth = myDate.getMonth()

      var m = tMonth + 1
      if (m.toString().length == 1) {
        m = '0' + m
      }
      this.datetime = tYear + '-' + m
      console.log(this.datetime)
    },
    show(index) {
      this.cleanForm()
      this.visible = true
      this.targetId = this.data[index].dataId
      let params = {
        targetId: this.targetId,
        patientId: this.queryParam.patientId
      }
      getAction(this.url.getTargetValue, params).then(res => {
        if (res.success) {
          this.form.setFieldsValue({
            targetName: res.result.targetName
          })
          this.bmi = res.result.bmi
          this.waist = res.result.waist
          this.heartRate = res.result.heartRate
          this.ldl = res.result.ldl
          this.hdl = res.result.hdl
          this.tg = res.result.tg
          this.tc = res.result.tc
          this.pressureHigh = res.result.pressureHigh
          this.pbg = res.result.pbg
          this.fbg = res.result.fbg
          this.hbA1c = res.result.hbA1c
          this.pressureLow = res.result.pressureLow
          this.weight = res.result.weight
          this.drug = res.result.drug
          this.alt = res.result.alt
          this.bil = res.result.bil
          this.ast = res.result.ast
          this.alp = res.result.alp
          this.uae = res.result.uae
          this.uae_24h = res.result.uae_24h
          this.acr = res.result.acr
          this.cr = res.result.cr
          this.ureanitrogen = res.result.ureanitrogen
          this.gfr = res.result.gfr
          this.crcl = res.result.crcl
          this.bua = res.result.bua

          if (this.bmi || this.weight || this.waist || this.heartRate || this.pressureHigh || this.pressureLow) {
            this.area1 = true
          } else {
            this.area1 = false
          }

          if (this.fbg || this.pbg || this.hbA1c) {
            this.area2 = true
          } else {
            this.area2 = false
          }

          if (this.tc || this.tg || this.ldl || this.hdl) {
            this.area3 = true
          } else {
            this.area3 = false
          }

          if (this.fbg || this.bil || this.ast || this.alp) {
            this.area4 = true
          } else {
            this.area4 = false
          }

          if (
            this.uae ||
            this.uae_24h ||
            this.acr ||
            this.cr ||
            this.ureanitrogen ||
            this.gfr ||
            this.crcl ||
            this.bua
          ) {
            this.area5 = true
          } else {
            this.area5 = false
          }
        }
      })
    },
    cleanForm() {
      this.form.setFieldsValue({
        targetName: ''
      })
      this.targetId = ''
      this.weight = ''
      this.drug = ''
      this.bmi = ''
      this.waist = ''
      this.heartRate = ''
      this.ldl = ''
      this.hdl = ''
      this.tg = ''
      this.tc = ''
      this.pressureHigh = ''
      this.pbg = ''
      this.fbg = ''
      this.hbA1c = ''
      this.pressureLow = ''
      this.alt = ''
      this.bil = ''
      this.ast = ''
      this.alp = ''
      this.uae = ''
      this.uae_24h = ''
      this.acr = ''
      this.cr = ''
      this.ureanitrogen = ''
      this.gfr = ''
      this.crcl = ''
      this.bua = ''
    },
    handleChange(value, key, column) {
      const newData = [...this.data]
      const target = newData.filter(item => key === item.key)[0]
      if (target) {
        target[column] = value
        this.data = newData
      }
    },
    edit(key) {
      const newData = [...this.data]
      const target = newData.filter(item => key === item.key)[0]
      this.editingKey = key
      if (target) {
        target.editable = true
        this.data = newData
      }
    },
    save(key) {
      const newData = [...this.data]
      const newCacheData = [...this.cacheData]
      const target = newData.filter(item => key === item.key)[0]
      const targetCache = newCacheData.filter(item => key === item.key)[0]
      if (target && targetCache) {
        delete target.editable
        this.data = newData
        Object.assign(targetCache, target)
        this.cacheData = newCacheData
      }
      this.editingKey = ''
    },
    cancel(key) {
      const newData = [...this.data]
      const target = newData.filter(item => key === item.key)[0]
      this.editingKey = ''
      if (target) {
        Object.assign(target, this.cacheData.filter(item => key === item.key)[0])
        delete target.editable
        this.data = newData
      }
    }
  }
}
</script>
<style scoped>
.editable-row-operations a {
  margin-right: 8px;
}

.ant-table-bordered .ant-table-thead > tr > th,
.ant-table-bordered .ant-table-tbody > tr > td {
  text-align: center;
}
.ant-drawer-mask {
  background-color: rgba(0, 0, 0, 0.045);
}

/* input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
  -webkit-appearance: none !important;
  margin: 0;
} */
</style>
